<!-- src/views/BookDetailView.vue -->
<template>
  <div class="book-detail-view">
    <el-container>
      <el-header>
        <div class="header-content">
          <h2>📚 图书详情</h2>
          <div class="header-buttons">
            <el-button @click="goBack">返回列表</el-button>
          </div>
        </div>
      </el-header>
      <el-main>
        <el-card class="book-card">
          <div class="book-info">
            <div class="info-grid">
              <div class="info-item">
                <span class="label">ISBN:</span>
                <span class="value">{{ book.isbn }}</span>
              </div>
              <div class="info-item">
                <span class="label">书名:</span>
                <span class="value">{{ book.title }}</span>
              </div>
              <div class="info-item">
                <span class="label">作者:</span>
                <span class="value">{{ book.author }}</span>
              </div>
              <div class="info-item">
                <span class="label">分类:</span>
                <span class="value">{{ book.genre }}</span>
              </div>
              <div class="info-item">
                <span class="label">出版日期:</span>
                <span class="value">{{ formatDate(book.publicationDate) }}</span>
              </div>
              <div class="info-item">
                <span class="label">状态:</span>
                <el-tag
                  :type="book.available ? 'success' : 'danger'"
                  effect="dark"
                  size="small"
                >
                  {{ book.available ? '可借阅' : '不可借阅' }}
                </el-tag>
              </div>
              <div class="info-item">
                <span class="label">库存:</span>
                <span class="value" :class="{ 'low-stock': book.availableCopies <= 2 }">
                  {{ book.availableCopies }} / {{ book.totalCopies }}
                </span>
              </div>
            </div>
          </div>

          <div class="action-buttons-group">
            <el-button
              type="warning"
              @click="showBorrowDialog"
              :disabled="!book.available || book.availableCopies <= 0"
              :icon="Upload"
            >
              借阅图书
            </el-button>
            <el-button
              type="danger"
              @click="deleteBook"
              :icon="Delete"
              style="margin-left: 16px;"
            >
              删除图书
            </el-button>
          </div>
        </el-card>

        <!-- 借阅记录 -->
        <el-card class="records-card" style="margin-top: 20px;">
          <template #header>
            <span>借阅记录</span>
          </template>
          <BorrowRecordsTable :records="borrowRecords" :loading="recordsLoading" />
        </el-card>

        <!-- 借阅对话框 -->
        <BorrowBookDialog
          ref="borrowDialogRef"
          :book="book"
          @confirm="handleBorrowConfirm"
        />
      </el-main>
    </el-container>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { createBookService } from '@/services/bookServiceFactory'
import { createBorrowService } from '@/services/borrowServiceFactory'
import { format } from 'date-fns'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Upload, Delete } from '@element-plus/icons-vue'
import BorrowRecordsTable from '@/components/BorrowRecordsTable.vue'
import BorrowBookDialog from '@/components/BorrowBookDialog.vue'

export default {
  name: 'BookDetailView',
  props: ['id'],
  components: {
    // eslint-disable-next-line vue/no-unused-components
    Upload,
    // eslint-disable-next-line vue/no-unused-components
    Delete,
    BorrowRecordsTable,
    BorrowBookDialog
  },
  setup(props) {
    const router = useRouter()
    const route = useRoute()
    const book = ref({})
    const borrowRecords = ref([])
    const loading = ref(false)
    const recordsLoading = ref(false)
    const bookService = createBookService()
    const borrowService = createBorrowService()
    const borrowDialogRef = ref(null)

    const formatDate = (dateString) => {
      if (!dateString) return ''
      return format(new Date(dateString), 'yyyy-MM-dd')
    }

    const loadBook = async () => {
      try {
        loading.value = true
        const bookId = props.id || route.params.id
        book.value = await bookService.getBookById(bookId)
      } catch (error) {
        console.error('Failed to load book:', error)
        ElMessage.error('图书不存在')
        router.push('/books')
      } finally {
        loading.value = false
      }
    }

    const loadBorrowRecords = async () => {
      try {
        recordsLoading.value = true
        const bookId = props.id || route.params.id
        borrowRecords.value = await borrowService.getRecordsByBookId(bookId)
      } catch (error) {
        console.error('加载借阅记录失败:', error)
        ElMessage.error('加载借阅记录失败')
      } finally {
        recordsLoading.value = false
      }
    }

    const goBack = () => {
      router.push('/books')
    }

    const showBorrowDialog = () => {
      borrowDialogRef.value.show()
    }

    const handleBorrowConfirm = async (borrowData) => {
      try {
        await borrowService.borrowBook(
          borrowData.bookId,
          borrowData.borrowerName,
          borrowData.borrowerPhone
        )
        ElMessage.success('借阅成功！')
        await loadBook()
        await loadBorrowRecords()
      } catch (error) {
        ElMessage.error('借阅失败: ' + error.message)
      }
    }

    const deleteBook = async () => {
      try {
        await ElMessageBox.confirm(
          `确定要删除《${book.value.title}》吗？此操作不可恢复！`,
          '删除确认',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          }
        )

        await bookService.deleteBook(book.value.id)
        ElMessage.success('图书删除成功！')
        router.push('/books')
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
        }
      }
    }

    onMounted(() => {
      loadBook()
      loadBorrowRecords()
    })

    return {
      book,
      borrowRecords,
      loading,
      recordsLoading,
      formatDate,
      goBack,
      showBorrowDialog,
      handleBorrowConfirm,
      deleteBook,
      borrowDialogRef,
      Upload,
      Delete
    }
  }
}
</script>

<style scoped>
.book-detail-view {
  height: 100vh;
}
.el-header {
  background-color: #f5f7fa;
  padding: 0 20px;
  border-bottom: 1px solid #ebeef5;
}
.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 60px;
}
.header-buttons {
  display: flex;
  gap: 12px;
}
.book-card {
  max-width: 800px;
  margin: 0 auto;
}
.book-info {
  margin-bottom: 30px;
}
.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-top: 20px;
}
.info-item {
  display: flex;
  flex-direction: column;
}
.label {
  font-weight: bold;
  color: #606266;
  margin-bottom: 4px;
  font-size: 14px;
}
.value {
  font-size: 16px;
  color: #303133;
}
.low-stock {
  color: #e6a23c;
  font-weight: bold;
}
.action-buttons-group {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}
@media (max-width: 600px) {
  .action-buttons-group {
    flex-direction: column;
  }
  .el-button-group {
    width: 100%;
  }
  .el-button-group .el-button {
    flex: 1;
  }
}
</style>